
// import { useHistory } from "react-router-dom";

// function NewTabLink() {
//   const history = useHistory();
  
//   const handleClick = () => {
//     const url = history.createHref({ pathname: "/about" }); // 生成完整 URL
//     window.open(url, "_blank", "noopener,noreferrer"); 
//   };

//   return <button onClick={handleClick}>在新标签页打开 About</button>;
// }

// export default NewTabLink;


import React, { useState } from 'react';
import { useHistory, useLocation } from 'react-router-dom';

// 自定义 Hook 用于跨标签页共享数据
function useCrossTabState(key, initialValue) {
  const [state, setState] = useState(() => {
    const saved = sessionStorage.getItem(key);
    return saved !== null ? JSON.parse(saved) : initialValue;
  });

  const setCrossTabState = (value) => {
    setState(value);
    sessionStorage.setItem(key, JSON.stringify(value));
    window.dispatchEvent(new Event('sessionStorageUpdate'));
  };

  React.useEffect(() => {
    const handleStorageChange = (e) => {
      if (e.key === key) {
        const saved = sessionStorage.getItem(key);
        if (saved !== null) {
          setState(JSON.parse(saved));
        }
      }
    };

    window.addEventListener('sessionStorageUpdate', handleStorageChange);
    window.addEventListener('storage', handleStorageChange);

    return () => {
      window.removeEventListener('sessionStorageUpdate', handleStorageChange);
      window.removeEventListener('storage', handleStorageChange);
    };
  }, [key]);

  return [state, setCrossTabState];
}

// 新标签页打开组件
function NewTabLink() {
  const history = useHistory();
  const [data, setData] = useState({});
  
  // 模拟要传递的数据
  const mockData = {
    userId: "U123456",
    userName: "张三",
    lastLogin: "2023-06-15",
    preferences: {
      theme: "dark",
      notifications: true
    }
  };

  const handleClick = () => {
    // 1. 生成唯一标识符
    const stateId = `state_${Date.now()}`;
    
    // 2. 存储数据到 sessionStorage
    setTimeout(() => {
      sessionStorage.setItem(stateId, JSON.stringify(mockData));

    }, 1000)
    
    // 3. 创建带参数的 URL
    const url = history.createHref({ 
      pathname: "/admin/about", 
      search: `?stateId=${stateId}`,
      state: { data: mockData } // 也可以通过 state 传递数据
    });
    
    // 4. 打开新标签页
    const newWindow = window.open(url, "_blank", "noopener,noreferrer");
    

    // 5. 添加关闭窗口时的清理逻辑
    // const timer = setInterval(() => {
    //   if (newWindow.closed) {
    //     clearInterval(timer);
    //     sessionStorage.removeItem(stateId);
    //   }
    // }, 500);
  };

  return (
    <div className="container">
      <div className="card">
        <h2>新标签页数据传递演示</h2>
        <button className="btn" onClick={handleClick}>
          在新标签页打开 About 页并传递数据
        </button>
        
        <div className="data-preview">
          <h3>将要传递的数据：</h3>
          <pre>{JSON.stringify(mockData, null, 2)}</pre>
        </div>
      </div>
    </div>
  );
}



export default NewTabLink